from odoo import fields, models, api, _
from odoo.tools.float_utils import float_compare, float_is_zero
from odoo.exceptions import UserError


class RegistrationGoodQty(models.Model):
    _name = 's.registration.good.qty.wizard'
    _description = 'Registration Good Qty'

    production_id = fields.Many2one('mrp.production', string='Current Production', readonly=True)
    workorder_id = fields.Many2one('mrp.workorder', 'Work Order', required=True)
    value_set = fields.Float('value_set', compute='_compute_qty')
    value_panel = fields.Float('value_panel', compute='_compute_qty')
    line_ids = fields.One2many('s.registration.good.qty.line.wizard', 'order_id')
    max_scrap_qty = fields.Float('Max Scrap Quantity', compute='_compute_qty')
    max_scrap_set_qty = fields.Float('Max Scrap SET Quantity', compute='_compute_qty')
    max_scrap_panel_qty = fields.Float('Max Scrap PANEL Quantity', compute='_compute_qty')
    min_scrap_qty = fields.Float('Min Scrap Quantity', compute='_compute_qty')
    min_scrap_set_qty = fields.Float('Min Scrap SET Quantity', compute='_compute_qty')
    min_scrap_panel_qty = fields.Float('Min Scrap PANEL Quantity', compute='_compute_qty')
    scrap_qty = fields.Float('Scrap Quantity')
    scrap_set_qty = fields.Float('Scrap SET Quantity')
    scrap_panel_qty = fields.Float('Scrap PANEL Quantity')

    @api.onchange('scrap_panel_qty')
    def onchange_scrap_panel_qty(self):
        self.scrap_qty = self.value_panel * self.scrap_panel_qty
        self.scrap_set_qty = self.scrap_qty / self.value_set

    @api.depends('line_ids')
    def _compute_qty(self):
        for rec in self:
            rec.value_set = rec.production_id.product_id.value_set
            rec.value_panel = rec.production_id.product_id.value_pnl
            rec.max_scrap_qty = min([sum(rec.line_ids.mapped('scrap_qty')), rec.production_id.product_qty])
            rec.max_scrap_set_qty = min([sum(rec.line_ids.mapped('scrap_set_qty')), rec.production_id.product_qty / rec.value_set])
            rec.max_scrap_panel_qty = min([sum(rec.line_ids.mapped('scrap_panel_qty')), rec.production_id.product_qty])

            rec.min_scrap_qty = max(rec.line_ids.mapped('scrap_qty'), default=0)
            rec.min_scrap_set_qty = max(rec.line_ids.mapped('scrap_set_qty'), default=0)
            rec.min_scrap_panel_qty = max(rec.line_ids.mapped('scrap_panel_qty'), default=0)

    def default_get(self, fields_list):
        res = super().default_get(fields_list)
        production_id = res.get('production_id')
        if not production_id:
            return res
        production_id = self.env['mrp.production'].browse(production_id)
        line_vals_list = []
        child_production_ids = production_id._get_children()
        child_production_ids |= production_id.s_child_production_ids
        for child in child_production_ids:
            if sum(child.workorder_ids.mapped('qty_op_reject')) > 0:
                line_vals_list.append((0, 0, {
                    'production_id': child.id,
                    'scrap_qty': sum(child.workorder_ids.mapped('qty_op_reject')),
                    'scrap_set_qty': sum(child.workorder_ids.mapped('qty_op_reject_set')),
                    'scrap_panel_qty': sum(child.workorder_ids.mapped('qty_op_reject_pnl'))
                }))
        res.update({'line_ids': line_vals_list})
        return res

    def action_confirm(self):
        self.ensure_one()
        rounding = self.production_id.product_uom_id.rounding
        if not self.production_id.s_not_scrap_verification:
            if float_compare(self.scrap_qty, self.max_scrap_qty, precision_rounding=rounding) == 1 or \
                    float_compare(self.scrap_panel_qty, self.max_scrap_panel_qty, precision_rounding=rounding) == 1:
                raise UserError(_('The registered scrap quantity is greater than the maximum allowable scrap quantity!'))

        # if float_compare(self.scrap_qty, self.min_scrap_qty, precision_rounding=rounding) == -1 or \
        #         float_compare(self.scrap_panel_qty, self.min_scrap_panel_qty, precision_rounding=rounding) == -1:
        #     raise UserError(_('The registered scrap quantity is less than the maximum allowable scrap quantity!'))

        self.production_id.write({'s_registered': True})
        reason = self.env['scrap.reason'].search([('name', '=', '首工序登记不良品')], limit=1)
        if not reason:
            reason = self.env['scrap.reason'].sudo().create({'name': '首工序登记不良品'})
        self.workorder_id.write({'s_scrap_ids': [(0, 0, {
            'scrap_reason_id': reason.id,
            'scrap_qty': self.scrap_qty,
            'scrap_set_qty': self.scrap_set_qty,
            'scrap_panel_qty': self.scrap_panel_qty
        })]})
        self.production_id.with_delay().scrap_warning()


class RegistrationGoodQtyLine(models.Model):
    _name = 's.registration.good.qty.line.wizard'
    _description = 'Registration Good Qty Line'

    order_id = fields.Many2one('s.registration.good.qty.wizard')
    production_id = fields.Many2one('mrp.production', string='Production', readonly=True)
    scrap_qty = fields.Float('Scrap Quantity', readonly=True)
    scrap_set_qty = fields.Float('Scrap SET Quantity', readonly=True)
    scrap_panel_qty = fields.Float('Scrap PANEL Quantity', readonly=True)
